{include file="$header" /}
<div class="mk-app-warp mk-card-tabs">
    <mk-table-header
	    keyword-title="名称关键词搜索"
        :add-url="addUrl"
        :del-url="delUrl"
        :rows="rows"
        @del="del()"
        @add="openDrawer()"
        @search="searchData($event)"
        expand
        @expand-all="expandAll($event)">
        <template v-slot:button>
        	<el-button 
                v-if="synchroAuthority && language !== langDefault"
                size="small" 
                icon="el-icon-warning-outline"
                type="warning" 
                @click="synchro()">
                <span class="title">同步</span>
            </el-button>
        </template>
    </mk-table-header>
    <el-table
        ref="table"
        :data="tableTree"
        v-loading="loading"
        @selection-change="checkSelected"
        @select-all="checkAll()"
        row-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="编号"></el-table-column>
        <el-table-column prop="title" label="名称"></el-table-column>
        <el-table-column prop="type" label="类型">
        	<template slot-scope="scope">
        		<el-select
                    v-model="scope.row.type"
                    size="small"
                    disabled>
                    <el-option
                        v-for="(item, index) in option"
                        :key="index"
                        :label="item.title"
                        :value="item.name">
                    </el-option>
                </el-select>
        	</template>
        </el-table-column>
        <el-table-column prop="show" label="显示">
        	<template slot-scope="scope">
        		<el-select @change="fieldEdit(scope.row, 'show')" v-model="scope.row.show" placeholder="请选择" size="small">
                    <el-option
                        v-for="item in showList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
        	</template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100px">
            <template slot-scope="scope">
                <el-switch
                    v-model="scope.row.status"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0"
                    @change="fieldEdit(scope.row, 'status')"
                    :disabled="editAuthority === false">
                </el-switch>
            </template>
        </el-table-column>
        <el-table-column prop="num" label="标识" width="80px">
        	<template slot-scope="scope">
                <el-input
		            size="small"
		            style="width: 70px"
                    v-model="scope.row.num"
                    @change="fieldEdit(scope.row, 'num')"
                    :disabled="editAuthority === false">
                </el-input>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
            <template slot-scope="scope">
                <mk-table-public
                    :edit-url="editUrl"
                    :del-url="delUrl"
                    :push-url="addUrl"
                    :copy-url="addUrl"
                    @edit="openDrawer(scope.row)"
                    @del="del(scope.row)"
                    @push="parentAppend(scope.row)"
                    @copy="copy(scope.row)">
                </mk-table-public>
            </template>
        </el-table-column>
    </el-table>
</div>
{include file="catalog/drawer" /}
{include file="$component" /}
<script>
	var group = {:json_encode($group)};
	new Vue({
	    el: '#app',
	    data() {
	        return {
	            rows: [],
	            option: {:json_encode($option)},
	            table: [],
	            tableTree: [],
	            tableTreeString: [],
	            search:{
                    keyword: "",
                },
	            url: "catalog/index",
	            addUrl: "catalog/save",
	            delUrl: "catalog/delete",
	            editUrl: "catalog/update",
	            synchroUrl: "catalog/synchro",
	            loading: false,
	            select: false,
			    linksTypeList: [
				    {label:'默认', value: 0,},
				    {label:'自定义链接',value: 1,},
			    ],
			    group: tree.convertString(group),
	            drawer: false,
	            showList: [
		            {label: "不显示", value: 0},
		            {label: "都显示", value: 1},
		            {label: "头部显示", value: 2},
		            {label: "底部显示", value: 3},
	            ],
	            drawerActiveName: "info",
	            drawerData: {},
	            drawerForm: {
	            	num: "",
			    	pid: "",
			    	group_id: [],
			        title: "",
			        type: "",
			        cover: "",
			        field: [],
			        content: "",
			        seo_url: "",
			        seo_title: "",
			        seo_keywords: "",
			        seo_description: "",
			        links_type: 0,
			        links_value: "",
			        status: 1,
			        show: 1,
			        sort:0,
			        mobile: 1,
			    },
	            drawerRules: {
			    	pid: [
			            { required: true, message: '请选择父级', trigger: 'blur' },
			        ],
			        title: [
			            { required: true, message: '请输入名称', trigger: 'blur' },
			            { min: 2, max: 255, message: '长度在 2 到 255 个字符', trigger: 'blur' }
			        ],
			        seo_url: [],
			        type: [
			            { required: true, message: '请选择类型', trigger: 'blur' },
			        ],
			        links_type: [
			            { required: true, message: '请选择链接类型', trigger: 'blur' },
			        ],
			        sort: [
                        { required: true, message: '请输入排序', trigger: 'blur' },
                        { type: 'number', message: '只允许纯数字', trigger: 'blur' },
                    ],
			    },
	            drawerLoading: false,
	        }
	    },
	    created () {
	    	this.getData();
	    },
	    computed: {
	    	editAuthority() {
	    		return authorityPath.indexOf(this.editUrl) !== -1;
	    	},
	    	synchroAuthority() {
		    	return authorityPath.indexOf(this.synchroUrl) !== -1
	    	},
	    },
	    methods: {
	    	/**
             * 获取数据
             */
	        getData() {
	            let self     = this;
	            self.loading = true;
	            request.post(self.url, self.search, function(res) {
	                self.loading    = false;
	                self.table      = res.data;
	                self.tableTree  = tree.convert(self.table);
	            });
	        },
	        /**
             * 向父类追加行
             * @param  {Object} row 当前行
             */
	        parentAppend(row) {
                let arr = JSON.parse(JSON.stringify(this.drawerForm));
                arr.type = row.type;
                arr.pid = row.id;
                this.openDrawer(arr);
            },
            /**
             * 复制
             * @param  {Object} row 当前行
             */
            copy(row) {
                let arr = JSON.parse(JSON.stringify(row));
                delete(arr['id']);
                this.openDrawer(arr);
            },
            /**
             * 打开抽屉
             * @param  {Object} row 当前行
             */
	        openDrawer(row = "") {
	            let self = this;
	            self.drawerData = row === "" ? JSON.parse(JSON.stringify(self.drawerForm)) : JSON.parse(JSON.stringify(row));
	            self.drawer = true;
	            self.drawerActiveName = "info";
	        },
	        /**
             * 保存内容
             */
	        saveDrawer() {
	            let self = this;
	            self.$refs.drawerData.validate((valid) => {
	                if (valid) {
	                    let requestUrl = typeof self.drawerData.id === 'undefined' ? self.addUrl : self.editUrl;
	                    self.drawerLoading = true;
	                    request.post(requestUrl, self.drawerData, function(res){
	                        self.drawerLoading = false;
	                        if (res.status === 'success') {
                                self.getData();
                                self.drawer = false;
                            } else {
                            	self.$message({ showClose: true, message: res.message, type: res.status});
                            }
	                    });
	                } else {
	                    return false;
	                }
	            });
	        },
	        /**
             * 行删除、批量删除
             * @param  {Object} row 当前行
             */
	        del(row = "") {
	            let self = this;
	            let ids  = row === "" ? common.arrayColumn(self.rows,'id') : [row.id]; 
	            self.$confirm('确定删除吗？', '', {
	                confirmButtonText: '确定',
	                cancelButtonText: '取消',
	                type: 'warning'
	            }).then(() => {
	                request.post(self.delUrl, {'ids': ids}, function(res){
	                	if (res.status === 'success') {
	                		self.getData();
	                	} else {
	                		self.$message({ showClose: true, message: res.message, type: res.status});
	                	}
	                });
	            }).catch(() => {});
	        },
	        /**
             * 单字段修改
             * @param  {Object} row 当前行
             */
	        fieldEdit(row, field) {
	        	let self = this;
	            request.post(self.editUrl, {id: row.id, value: row[field], fieldName: field}, function(res) {
	            	if (res.status != 'success') {
                        self.$message({ showClose: true, message: res.message, type: res.status});
                        self.getData();
                    }
                });
	        },
	        /**
             * 关键词搜索
             * @param  {Object} value 搜索内容
             */
	        searchData(value) {
	            this.search = Object.assign({}, this.search, {keyword: value.keyword});
	        },
	        /**
             * 选中行
             * @param  {Object} rows 多行数
             */
	        checkSelected(rows) {
	            this.rows = rows;
	        },
	         /**
             * 选中所有行，只有树形结构才需要这样处理
             */
	        checkAll() {
	            let self    = this;
	            let table  = self.$refs.table;
	            self.select = self.select ? false : true;
	            self.table.forEach(function (item, index){
	                table.toggleRowSelection(item, self.select);
	            });
	        },
	         /**
             * 折叠/展开所有行，只有树形结构才需要这样处理
             */
	        expandAll(bool) {
	            let self    = this;
	            let $table  = self.$refs.table;
	            self.table.forEach(function (item, index){
	                $table.toggleRowExpansion(item, bool);
	            });
	        },
	        /**
	         * 同步主语言数据
	         * @param  {string} name 需要同步的数据，空代表全部
	         */
	        synchro() {
	        	let self = this;
	        	self.$confirm('同步主语言后，当前语言的数据将不存在，确定同步吗？', '', {
	                confirmButtonText: '确定',
	                cancelButtonText: '取消',
	                type: 'warning'
	            }).then(() => {
		        	request.post(self.synchroUrl, {}, function(res) {
	                    self.$message({ showClose: true, message: res.message, type: res.status });
	                    self.getData();
	                });
                }).catch(() => {});
	        },
	        typeChange() {
	    		if (this.drawerData.type === 'page') {
	    			this.drawerRules.seo_url = [
				        { pattern: /^[A-Za-z0-9_\-]+$/ig, message: '只能为字母和数字，下划线_及破折号-', trigger: 'blur' },
				        { required: true, message: '请输入页面地址', trigger: 'blur' },
				        { min: 2, max: 255, message: '长度在 3 到 255 个字符', trigger: 'blur' }
			        ];
	    		} else {
	    			this.drawerRules.seo_url = [
				        { pattern: /^[A-Za-z0-9_\-]+$/ig, message: '只能为字母和数字，下划线_及破折号-', trigger: 'blur' }
			        ];
	    		}
                // 显示对应类型的上级，如果不是对应上级请自定义链接
                let self = this;
                let parentList = [];
	            self.table.forEach(function (item, index) {
	                if (item.id !== self.drawerData.id) {
	                    parentList.push(item);
	                }
	            });
	            self.tableTreeString = tree.convertString(parentList);
	            self.tableTreeString.unshift({id: 0, title: "最父级"});
	    	},
	    },
	    watch: {
	    	drawer(v) {
                this.$nextTick(()=>{
                    if(! v){
                        // 重置表单
                        this.$refs.drawerData.resetFields();
                    } else {
                    	this.typeChange();
                    }
                })
            },
            search() {
                this.getData();
            }
	    }
	})
</script>
{include file="$footer" /}